﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows;

namespace PTExpress.DataAccess
{
    public class UserAccess
    {
        static public string username = string.Empty;
        static public string tableName = "TaiKhoan";

        //Mã hóa MẬT KHẨU
        public static string sha1(string pass)
        {
            System.Text.Encoding enc = System.Text.Encoding.ASCII;
            byte[] myByteArray = enc.GetBytes(pass);
            return enc.GetString(System.Security.Cryptography.SHA1.Create().ComputeHash(myByteArray));
        }

        //Lấy thông tin user
        static public DataTable GetUserInfo(string username)
        {
            return DataProvider.QueryResults("SELECT username,password FROM " + tableName + " WHERE username = '" + username + "'").Tables[0];
        }

        //Kiểm tra đăng nhập
        static public bool Login(string user, string pass)
        {
            username = user;
            return DataProvider.QueryResults("select * from " + tableName + " where username = '" + user + "' and password = '" + sha1(pass) + "'").Tables[0].Rows.Count > 0;
        }

        //Thay đổi mật khẩu
        static public bool ThayDoiMatKhau(string username, string newPassword)
        {
            try
            {
                DataProvider.RunExecute("UPDATE " + tableName + " SET password = '" + sha1(newPassword) + "' WHERE username = '" + username + "'");
            }
            catch
            {
                return false;
            }
            return true;
        }
        //Nhớ paswword
        static public void RememberLogin(bool active)
        {
            if (string.IsNullOrEmpty(username))
                return;
            if (DataProvider.QueryResults("select * from RememberLogin where id = 1").Tables[0].Rows.Count > 0)
                DataProvider.RunExecute("Update RememberLogin set username = '" + username + "' , date = '" + String.Format("{0:yyyyMMdd}", DateTime.Now) + "' , active = '" + active.ToString() + "' where id = 1");
            else
                DataProvider.RunExecute("insert into RememberLogin(id,username,date,active) values (1,'" + username + "','" + String.Format("{0:yyyyMMdd}", DateTime.Now) + "','" + active.ToString() + "')");
        }

        //Kiểm tra nhớ mật khẩu
        static public bool CheckRememberLogin()
        {
            DataTable tb = DataProvider.QueryResults("select * from RememberLogin").Tables[0];
            if (tb.Rows.Count == 0)
                return false;
            if (tb.Rows[0]["active"].ToString().ToUpper() != "TRUE")
                return false;
            if ((DateTime.Parse(tb.Rows[0]["date"].ToString()).AddDays(3) <= DateTime.Now))
                return false;
            username = tb.Rows[0]["username"].ToString();
            return true;
        }

        //Lấy Username đăng nhập gần nhất
        static public string GetOldUsername()
        {
            if (string.IsNullOrEmpty(DataProvider.ConnectionString))
                return string.Empty;
            DataTable tb = DataProvider.QueryResults("select * from RememberLogin").Tables[0];
            if (tb.Rows.Count <= 0)
                return string.Empty;
            return tb.Rows[0]["username"].ToString();
        }

        //Lưu lại lịch sử đăng nhập của User
        static public bool SaveLogin()
        {
            if (string.IsNullOrEmpty(username))
                return false;
            DataTable tb = DataProvider.QueryResults("select '' as time, '' as date,username,tennv from v_dmNguoiDung where username= '" + username + "'").Tables[0];
            if (tb.Rows.Count <= 0)
                return false;
            tb.Rows[0]["time"] = DateTime.Now.ToString("HH:mm:ss");
            tb.Rows[0]["date"] = DateTime.Now.ToString("dd/MM/yyyy");

            if (!System.IO.File.Exists("data\\log.xml"))
                tb.WriteXml("data\\log.xml", XmlWriteMode.WriteSchema);
            else
            {
                tb.ReadXml("data\\log.xml");
                tb.WriteXml("data\\log.xml", XmlWriteMode.WriteSchema);
            }
            return true;
        }

        //Load History Login
        static public DataTable LoadHistoryLogin()
        {
            DataTable tb = new DataTable();
            try
            {
                if (!System.IO.File.Exists("data\\log.xml"))
                    return tb;
                tb.ReadXml("data\\log.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " \nKhông thể đọc file log.xml", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return tb;
        }

        //Save History login
        static public void ClearHistory()
        {
            DataTable tb = new DataTable();
            if (!System.IO.File.Exists("data\\log.xml"))
                return;
            tb.ReadXml("data\\log.xml");
            tb.Rows.Clear();
            tb.WriteXml("data\\log.xml", XmlWriteMode.WriteSchema);
        }
    }
}
